<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php





class EOAuthUtils extends EOAuthComponent {
	
	private function __construct() {}

	
	public static function GetRequestToken(OAuthConsumer $consumer, $scope,
	$endpoint, $applicationName, $callbackUrl) {
		$signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();

				$params = array();
				if (isset($applicationName)) {
					}
		if (isset($callbackUrl)) {
			$params['oauth_callback'] = $callbackUrl;
		}
				$request = OAuthRequest::from_consumer_and_token($consumer, NULL, 'GET',
		$endpoint, $params);
		$request->sign_request($signatureMethod, $consumer, NULL);

				return self::GetTokenFromUrl($request->to_url());
	}
	
	public static function GetVerificationCode4MiniyunWeb(OAuthToken $token, $endpoint,$userName,$password) {
		$device_type="1";
		$device_name="web";
		$device_info=$userName;
		$url = $endpoint . "?oauth_token=" . $token->key."&user_name=".$userName."&password=".$password."&device_type=".$device_type."&device_name=".$device_name."&device_info=".$device_info;
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$code = curl_exec($ch);
		$headers = curl_getinfo($ch);
		curl_close($ch);

		if ($headers['http_code'] != 200) {
			throw new OAuthException($code);
		}
		return $code;
	}

	
	public static function GetAuthorizationUrl(OAuthToken $token, $endpoint) {
		return $endpoint . "?oauth_token=" . $token->key;
	}

	
	public static function GetAccessToken(OAuthConsumer $consumer,
	OAuthToken $token, $verifier, $endpoint) {
		$signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();

				$params = array();
		$params['oauth_verifier'] = $verifier;

				$request = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET',
		$endpoint, $params);
		$request->sign_request($signatureMethod, $consumer, $token);

				return self::GetTokenFromUrl($request->to_url());
	}

	
	private static function GetTokenFromUrl($url) {
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response = curl_exec($ch);
		$headers = curl_getinfo($ch);
		curl_close($ch);

		if ($headers['http_code'] != 200) {
			throw new OAuthException($response);
		}

		return self::GetTokenFromQueryString($response);
	}

	
	private static function GetTokenFromQueryString($queryString) {
		$values = array();
		parse_str($queryString, $values);
		return new OAuthToken($values['oauth_token'],
		$values['oauth_token_secret']);
	}
}
